<template>
  <a-modal :visible='visible' :maskClosable='false' @cancel='hideModal' :width="width+'mm'">
    <a-spin :spinning='spinning' style='min-height: 100px'>
      <div id='preview_content_custom'></div>
    </a-spin>
    <template slot='title'>
      <a-space>
        <div style='margin-right: 20px'>打印预览</div>
      </a-space>
    </template>
    <template slot='footer'>
      <!--      <a-button :loading='waitShowPrinter' type='primary' icon='printer' @click.stop='print'>打印</a-button>-->
      <!--      <a-button type='primary' icon='printer' @click.stop='toPdf'>pdf</a-button>-->
      <a-button key='close' type='info' @click='hideModal'>
        关闭
      </a-button>
    </template>
  </a-modal>
</template>

<script>
import { hiprint } from "./js/index"
import TaskRunner from "concurrent-tasks"

export default {
  name: "FlymePrintView",
  props: {},
  data() {
    return {
      visible: false,
      spinning: true,
      waitShowPrinter: false,
      // 纸张宽 mm
      width: 0,
      // 模板
      hiprintTemplate: {},
      // 数据
      printData: {}
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    hideModal() {
      this.visible = false
    },
    printView(template, printData, width = "210") {
      let hiprintObj = new hiprint.PrintTemplate({
        template: template.json,
        dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
        history: false // 是否需要 撤销重做功能
      })
      this.hiprintTemplate = hiprintObj
      this.visible = true
      this.spinning = true
      console.info("printView", hiprintObj)
      this.width = hiprintObj.printPanels ? hiprintObj.printPanels[0].width : width
      this.printData = printData
      this.$nextTick(() => {
        // eslint-disable-next-line no-undef
        $("#preview_content_custom").html(hiprintObj.getHtml(printData))
        this.spinning = false
      })
    },
    show(hiprintTemplate, printData, width = "210") {
      this.visible = true
      this.spinning = true
      console.info("show", hiprintTemplate)
      this.width = hiprintTemplate.editingPanel ? hiprintTemplate.editingPanel.width : width
      this.hiprintTemplate = hiprintTemplate
      this.printData = printData
      setTimeout(() => {
        // eslint-disable-next-line no-undef
        console.info("hiprintTemplate", hiprintTemplate.getHtml(printData))
        $("#preview_content_custom").html(hiprintTemplate.getHtml(printData))
        this.spinning = false
      }, 500)
    },
    print() {
      this.waitShowPrinter = true
      console.info("hiprintTemplate", this.hiprintTemplate)
      console.info("printData", this.printData)
      this.hiprintTemplate.print(this.printData, {}, {
        callback: () => {
          this.waitShowPrinter = false
        }
      })
    },
    print2(options) {
      let check = this.checkSocket()
      if (check) {
        let templateObj = options.template
        let hiprintObj = new hiprint.PrintTemplate({
          template: templateObj.json,
          dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
          history: false // 是否需要 撤销重做功能
        })
        let printerName = templateObj.printerName || ""
        hiprintObj.print2(options.printData, { printer: printerName, title: options.title })
        hiprintObj.on("printSuccess", (data) => {
          options.printSuccess && options.printSuccess(data)
        })
        return
      }
    },
    printByCount(options) {
      let check = this.checkSocket()
      if (check) {
        let templateObj = options.template
        let hiprintObj = new hiprint.PrintTemplate({
          template: templateObj.json,
          dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
          history: false // 是否需要 撤销重做功能
        })
        let printerName = templateObj.printerName || ""
        hiprintObj.print2(options.printData, { printer: printerName, title: options.title, copies: options.printCount })
        hiprintObj.on("printSuccess", (data) => {
          options.printSuccess && options.printSuccess(data)
        })
        return
      }
    },
    /**
     * 批量打印
     * @param template
     * @param printDataList
     * @param printSuccess
     */
    batchPrint(template, printDataList, printSuccess) {
      let check = this.checkSocket()
      if (check) {
        const runner = new TaskRunner()
        // 同时执行数量
        runner.setConcurrency(1)
        const task = []
        let that = this
        const tasksKey = `open${Date.now()}`
        for (let i = 1; i <= printDataList.length; i++) {
          let printData = printDataList[i - 1]
          // done -> 任务完成回调
          let key = `订单${printData.outOrderNo}`
          task.push(done => {
            that.realPrint(template, runner, done, key, i, i, printData, tasksKey, printSuccess)
          })
        }
        runner.addMultiple(task)
        this.openNotification(runner, tasksKey)
      }
    },
    /**
     * 批量打印
     * @param template
     * @param printDataList
     * @param countKey 指定单张打印次数
     * @param printSuccess
     */
    batchPrintByCount(options) {
      let { template, dataList, countKey, printCount, printSuccess, countVal } = options
      let check = this.checkSocket()
      if (check) {
        const runner = new TaskRunner()
        // 同时执行数量
        runner.setConcurrency(1)
        const task = []
        let that = this
        const tasksKey = `open${Date.now()}`
        for (let i = 1; i <= dataList.length; i++) {
          let c = 1
          let printData = dataList[i - 1]
          let count = countKey && printData[countKey] || printCount || 1
          if (countVal) {
            count = countVal
            printData[countKey] = count
          }
          for (let j = 1; j <= count; j++) {
            // done -> 任务完成回调
            let key = `订单${printData.outOrderNo}-${i}-${j}`
            task.push(done => {
              that.realPrint(template, runner, done, key, i, j, printData, tasksKey, printSuccess)
            })
          }
        }
        runner.addMultiple(task)
        this.openNotification(runner, tasksKey)
      }
    },
    realPrint(template, runner, done, key, i, c, printData, tasksKey, printSuccess) {
      let that = this
      that.$notification.info({
        key: key,
        placement: "topRight",
        duration: null,
        message: `正在准备打印第 ${c} 张`,
        description: "打印中..."
      })
      let templateObj = template
      let hiprintTemplate = new hiprint.PrintTemplate({
        template: templateObj.json
      })
      let printerName = templateObj.printerName || ""
      hiprintTemplate.print2(printData, { printer: printerName, title: key })
      hiprintTemplate.on("printSuccess", () => {
        let info = runner.tasks.list && runner.tasks.list.length > 1 ? "准备打印下一张" : "已完成打印"
        that.$notification.success({
          key: key,
          placement: "topRight",
          message: key + " 打印成功",
          description: info
        })
        printSuccess && printSuccess(printData)
        done()
        if (!runner.isBusy()) {
          that.$notification.close(tasksKey)
        }
      })
      hiprintTemplate.on("printError", function() {
        that.$notification.close(key)
        done()
        that.$message.error("打印失败，已加入重试队列中")
        runner.add(that.realPrint(runner, done, key, i, printData))
      })
    },
    openNotification(runner, tasksKey) {
      let that = this
      that.$notification.open({
        key: tasksKey,
        message: "打印中...",
        duration: 0,
        placement: "topLeft",
        description: "点击关闭所有打印任务",
        btn: h => {
          return h(
            "a-button",
            {
              props: {
                type: "danger",
                size: "small"
              },
              on: {
                click: () => {
                  that.$notification.close(tasksKey)
                  // 详情请查阅文档
                  runner.removeAll()
                  that.$message.info("已移除所有打印任务")
                }
              }
            },
            "关闭打印任务"
          )
        }
      })
    },
    checkSocket() {
      if (window.hiwebSocket.opened) {
        return true
      }
      this.$error({
        title: "客户端未连接",
        content: (h) => (
          <div>
            连接【{hiwebSocket.host}】失败！
            <br />
            请确保目标服务器已
            <a href='http://113.56.24.212:81/base/static/file/SBL-Print_win_x64-1.0.9.exe' target='_blank'>
              下载
            </a>
            并
            <a href='hiprint://' target='_blank'>
              运行
            </a>
            打印服务！
          </div>
        )
      })
      return false
    },
    toPdf() {
      this.hiprintTemplate.toPdf(this.printData, "打印预览pdf")
    }
  }
}

</script>
<style lang='less' scoped>

/deep/ .ant-modal-body {
  padding: 0px;
}

/deep/ .ant-modal-content {
  margin-bottom: 24px;
}
</style>
